package com.yishuifengxiao.common.social.weixin.connect.factoty;

import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;

import com.yishuifengxiao.common.social.weixin.adapter.WechatAdapter;
import com.yishuifengxiao.common.social.weixin.api.Wechat;
import com.yishuifengxiao.common.social.weixin.connect.provider.WechatServiceProvider;
import com.yishuifengxiao.common.social.weixin.entity.WechatAccessGrant;

/**
 * 微信登陆连接工厂
 * 
 * @author yishui
 * @version 1.0.0
 * @since 1.0.0
 */
public class WechatConnectionFactory extends OAuth2ConnectionFactory<Wechat> {

	public WechatConnectionFactory(String providerId, String appId, String appSecret) {
		super(providerId, new WechatServiceProvider(appId, appSecret), new WechatAdapter());
	}

	@Override
	protected String extractProviderUserId(AccessGrant accessGrant) {
		// 由于微信的openId是和accessToken一起返回的，所以在这里直接根据accessToken设置providerUserId即可，不用像QQ那样通过QQAdapter来获取
		if (accessGrant instanceof WechatAccessGrant) {
			return ((WechatAccessGrant) accessGrant).getOpenId();
		}
		return null;
	}

	@Override
	public Connection<Wechat> createConnection(AccessGrant accessGrant) {
		return new OAuth2Connection<Wechat>(getProviderId(), extractProviderUserId(accessGrant),
				accessGrant.getAccessToken(), accessGrant.getRefreshToken(), accessGrant.getExpireTime(),
				getOauth2ServiceProvider(), getApiAdapter(extractProviderUserId(accessGrant)));
	}

	@Override
	public Connection<Wechat> createConnection(ConnectionData data) {
		return new OAuth2Connection<Wechat>(data, getOauth2ServiceProvider(), getApiAdapter(data.getProviderUserId()));
	}

	private ApiAdapter<Wechat> getApiAdapter(String providerUserId) {
		return new WechatAdapter(providerUserId);
	}

	protected OAuth2ServiceProvider<Wechat> getOauth2ServiceProvider() {
		return (OAuth2ServiceProvider<Wechat>) getServiceProvider();
	}

}